<template>
  <div
    :class="isBg ? 'box_bg box' : 'box'"
    :style="{
      height: height,
    }"
  >
    <div v-if="!isShow" class="flex-x flex-center no_dev">请选择设备</div>
    <div
      element-loading-background="rgba(0, 0, 0, 0.1)"
      v-loading="loading"
      style="height: 100%"
      class="chart"
      ref="chart"
    ></div>
  </div>
</template>

<script>
import initMqtt from "@/views/common/js/device/mqttUtils.js";
import _ from "lodash";
import { useOption } from "./chartOption";
import { getMeasurements } from "@/api/assignments";
const filterName = ["TemperatureGuan", "TemperatureRe", "time", "now_temp"];
import { TENANT_TITLE } from "@/utils/local";
export default {
  name: "Chart",
  props: {
    height: {
      type: String,
      default: "55%",
    },
    tokens: {
      type: Object,
      default: () => {
        return {
          check: true,
          color: null,
          data: [],
          devName: "Z2",
          distributionToken: "d0e2168d-15e4-4f36-b134-13cab4f64266",
          id: "8e1bca02-b67e-46c5-86ba-4d801a58d558",
          name: "Z2",
          token: "01",
          type: 5,
        };
      },
    },
  },
  watch: {
    async tokens(newVal) {
      console.log("newVal :>> ", newVal);
      if (newVal.check) {
        this.isShow = true;
        if (this.client) {
          this.initmqtt.disconnect();
        }
        this.hisInit();
      } else {
        this.isShow = false;
        if (this.client) {
          this.initmqtt.disconnect();
        }
        if (this.lineChart) {
          this.lineChart.clear();
        }
      }
    },
  },
  data() {
    return {
      loading: false,
      chart: null,
      data: [],
      isBg: false,
      data2: [],
      data1: [],
      time2: [],
      timeTicket: null,
      option: {},
      time: 0,
      zoomStart: 50,
      zoomEnd: 100,
      ishistory: false,
      client: "",
      series: [],
      isShow: false,
      yAxis: [],
      dataZoomId: "",
      // tokens: [
      //   {
      //     devName: "Z2",
      //     token: "01",
      //     distributionToken: "d0e2168d-15e4-4f36-b134-13cab4f64266",
      //     data: [],
      //   },
      //   {
      //     devName: "Z6",
      //     token: "02",
      //     distributionToken: "5118246e-bb9f-434b-bf3e-989aea022536",
      //     data: [],
      //   },
      // ],
      colorList: [
        "#65f5f3",
        "#277ace",
        "#9D88FF",
        "#F8806C",
        "#D689FF",
        "#FFC64E",
        "#3AED9E",
        "#3DADFE",
      ],
      legendData: [],
    };
  },
  computed: {
    useTenantName() {
      switch (this.$store.getters.tenant.name) {
        case TENANT_TITLE[2]:
          return "精铸厂电炉中央温控系统生产可视化看板";
        default:
          return "热表处理厂中央集控系统生产可视化看板";
      }
    },
  },
  async mounted() {
    this.$nextTick(() => {
      this.lineChart = this.$echarts.init(this.$refs.chart);
    });
    // this.hisInit();
  },
  methods: {
    async hisInit() {
      // this.loading = true;
      const res = await this.getAssignmentsByToken(
        this.tokens.distributionToken
      );
      console.log("res :>> ", res);
      this.time2 = res.map((item) => {
        return item.eventDate;
      });
      let arr = [];
      res.map((item) => {
        for (const key in item.metadata) {
          const element = item.metadata[key];
          // 测试数据,把token过滤掉(不是数字不能渲染折线图)
          if (filterName.includes(key)) {
            const aIndex = arr.findIndex((a) => a.name == key);
            if (aIndex == -1) {
              arr.push({
                name: key,
                data: [element],
              });
            } else {
              arr[aIndex].data.push(element);
            }
          }
        }
      });
      console.log("arr :>> ", arr);
      if (arr.length) {
        this.option = useOption(
          arr,
          this.time2,
          {
            start: this.zoomStart,
            end: this.zoomEnd,
          },
          ""
        );

        this.init();
        this.receiveData();
      } else {
        this.$msg("暂无数据");
      }

      this.loading = false;
    },
    //mqtt初始化
    receiveData() {
      var param = {
        // url:  process.env.VUE_APP_MQTT_WS_URL + process.env.VUE_APP_MQTT_WS_API,
        url: process.env.VUE_APP_MQTT_WS_URL + process.env.VUE_APP_MQTT_WS_API,
      };
      this.tenantToken = this.$store.state.user.tenant.token;
      this.tenantTopic = `$avic/superlink/iot/${this.tenantToken}/${this.tokens.token}/measurement`;
      this.initmqtt = new initMqtt(param);
      // this.loading = true;
      console.log("this.tenantTopic :>> ", this.tenantTopic);
      this.client = this.initmqtt.connect(() => {
        console.log("mqtt连接成功,开始订阅主题");
        // this.loading = false;
        this.client.subscribe(this.tenantTopic);
        this.onMessageArrived();
      });
    },
    //接收数据
    onMessageArrived() {
      this.client.on("message", (topic, message) => {
        var obj = JSON.parse(message.toString());
        if (obj.type == "DeviceMeasurement") {
          const { request, deviceToken } = obj;
          // x轴 时间

          this.option.xAxis[0].data.push(request.eventDate);
          for (const key in request.metadata) {
            const element = request.metadata[key];
            // 测试数据,把token过滤掉(不是数字不能渲染折线图)
            if (filterName.includes(key)) {
              this.option.series.forEach((it, index) => {
                if (it.name == key) {
                  this.option.series[index].data.push(element);
                }
              });
            }
          }
          if (this.dataZoomId == "dataZoomX") {
            this.option.dataZoom[1].start = this.zoomStart;
            this.option.dataZoom[1].end = this.zoomEnd;
          }
          if (this.dataZoomId == "dataZoomY") {
            this.option.dataZoom[0].start = this.zoomStart;
            this.option.dataZoom[0].end = this.zoomEnd;
          }

          this.lineChart.setOption(this.option);
        }
      });
    },

    // 获取设备详情
    getAssignmentsByToken(token) {
      return new Promise((resolev, reject) => {
        var params = {
          page: 1,
          pageSize: 10,
        };
        getMeasurements(params, token).then((res) => {
          const { results } = res.data;
          resolev(results);
        });
      });
    },

    async init() {
      const that = this;
      // this.zoomStart = 50;
      // this.zoomEnd = 100;

      // addMarkLine this.lineChart.dispose()
      this.lineChart.on("dataZoom", function (event) {
        console.log("that.zoomStart :>> ", event.batch, event);
        that.dataZoomId = event.dataZoomId;
        if (event.batch) {
          that.zoomStart = event.batch[0].start;
          that.zoomEnd = event.batch[0].end;
        } else {
          that.zoomStart = event.start;
          that.zoomEnd = event.end;
        }
      });
      this.lineChart.setOption(this.option, true);
    },
    openDrawer() {
      // this.isBg = !this.isBg;
    },
  },
};
</script>

<style scoped lang='scss'>
.fill {
  /* height: 320px; */
  height: 100%;
  width: 100%;
}

.box {
  border: 1px solid #0da9f2;
  display: flex;
  flex-flow: column;
  height: 55%;
  width: 100%;
  position: relative;
  .no_dev {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #5dcbff;
  }
  .icons {
    position: absolute;
    left: 20px;
    top: 5px;
    z-index: 2;
    color: #5dcbff;
    font-size: 18px;
    cursor: pointer;
  }
}
.box_bg {
  position: absolute;
  left: 20%;
  z-index: 999;
  width: 80%;
  height: 76%;
}
.box .row.header {
  flex: 0 1 auto;
}

.box .row.content {
  flex: 1 1 auto;
}
</style>
